/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ReferenceForm.java
 *
 * Created on 14 févr. 2012, 22:41:29
 */
package app.views;

import app.App;
import app.models.Categorie;
import app.models.Reference;
import app.views.AddReferencePan.ImageFileFilter;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import org.jdesktop.swingx.JXImagePanel.Style;

/**
 * @todo add disponible?
 * @author Ghost
 */
public class ReferenceForm extends javax.swing.JDialog {
    
    private ArrayList<Categorie> categories = new ArrayList<Categorie>();

    private Reference selectedReference;
    
    /** Creates new form ReferenceForm */
    public ReferenceForm(final Reference ref) {
        super();
        setAlwaysOnTop(true);
        setModal(true);
        initComponents();
        computeCbCategories(App.getInstance().getCatalogue().getCategories());
        this.setLocationRelativeTo(null);
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                doCancel();
            }
        });
        
        this.setReference(ref);
    }
   
    
    /**
     * Set the reference and synchronize the ui
     * @param ref 
     */
    public void setReference(final Reference ref){
        this.selectedReference = ref;
        if(ref == null){
            this.setTitle("Référence form!");
            txtDesignation.setText("");
            txtPxAchat.setText("0.00");
            txtPxVente.setText("0.00");
            txtStock.setText("0");
            txtVendu.setText("0");
            cbCategories.setSelectedIndex(-1);
            imagePan.setImage(App.createPhoto(ref.getPhoto().getFileName()));
        } else {
            this.setTitle("Modification de la réference: " + ref.getDesignation());
            txtDesignation.setText(ref.getDesignation());
            txtPxAchat.setText(String.valueOf(ref.getPxAchatHT()));
            txtPxVente.setText(String.valueOf(ref.getPxVenteTTC()));
            txtStock.setText(String.valueOf(ref.getStock()));
            txtVendu.setText(String.valueOf(ref.getVendu()));
            cbCategories.setSelectedIndex(categories.indexOf(ref.getCategorie()));
            String filename = "aucune";
            if(!"".equals(ref.getPhoto().getFileName())){
                filename = ref.getPhoto().getFileName();
            }
            imagePan.setImage(App.createPhoto(filename));
            txtFileName.setText(filename);
        }
    }
    
    public Reference showDialog(){
        setVisible(true);
        return selectedReference;
    }
    
    private void computeCbCategories(List<Categorie> cats){
        //clearing possibles elements
        ((DefaultComboBoxModel)cbCategories.getModel()).removeAllElements();
        categories = new ArrayList<Categorie>();
        System.out.println("ajotu de " + cats.size() + " catégories");
        //addings news
        for(Categorie cat : cats){
            cbCategories.addItem(cat.getLibelle());
            categories.add(cat);
        }
    }

    private void doCancel(){
        this.selectedReference = null;
        this.dispose();
    }
    
    private void doAccept(){
        try{
            Categorie cat;
            
            if(cbCategories.getSelectedIndex() < 0){
                cat = new Categorie((String)cbCategories.getSelectedItem());
            } else {
                cat = categories.get(cbCategories.getSelectedIndex());
            }
            
            selectedReference.setCategorie(cat);
            selectedReference.setDesignation(txtDesignation.getText());
            selectedReference.setStock(Integer.parseInt(txtStock.getText()));            
            selectedReference.setPxAchatHT(Double.parseDouble(txtPxAchat.getText()));    
            selectedReference.setPxVenteTTC(Double.parseDouble(txtPxVente.getText()));
            selectedReference.setVendu(Integer.parseInt(txtVendu.getText()));
            
            
            
            this.dispose();
        } catch(NumberFormatException nfe){
            App.displayMessage("Erreur dans la saisie des nombres!", App.MESSAGE_TYPE.ERROR);
        }
    }
    
    public static void main(String[] args){
        ReferenceForm ref = new ReferenceForm(null);
        ref.setVisible(true);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btCancel = new javax.swing.JButton();
        btOk = new javax.swing.JButton();
        imagePan = new org.jdesktop.swingx.JXImagePanel();
        fileChooser = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtDesignation = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPxAchat = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtPxVente = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtStock = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtVendu = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        cbCategories = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        txtFileName = new javax.swing.JTextField();
        btPix = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btCancel.setText("Annuler");
        btCancel.setBorderPainted(false);
        btCancel.setContentAreaFilled(false);
        btCancel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelActionPerformed(evt);
            }
        });

        btOk.setIcon(App.createIcon("resources/accept.png"));
        btOk.setText("Enregistrer");
        btOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btOkActionPerformed(evt);
            }
        });

        imagePan.setBackground(new java.awt.Color(204, 204, 204));
        imagePan.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        imagePan.setDefaultImage(null);

        javax.swing.GroupLayout imagePanLayout = new javax.swing.GroupLayout(imagePan);
        imagePan.setLayout(imagePanLayout);
        imagePanLayout.setHorizontalGroup(
            imagePanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 295, Short.MAX_VALUE)
        );
        imagePanLayout.setVerticalGroup(
            imagePanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 235, Short.MAX_VALUE)
        );

        jLabel1.setText("Désignation : ");

        jLabel2.setText("Prix d'achat :");

        txtPxAchat.setMinimumSize(new java.awt.Dimension(60, 20));
        txtPxAchat.setPreferredSize(new java.awt.Dimension(60, 20));

        jLabel3.setText("Prix de vente : ");

        txtPxVente.setMinimumSize(new java.awt.Dimension(60, 20));
        txtPxVente.setPreferredSize(new java.awt.Dimension(60, 20));

        jLabel4.setText("Qte en stock : ");

        txtStock.setMinimumSize(new java.awt.Dimension(60, 20));
        txtStock.setPreferredSize(new java.awt.Dimension(60, 20));

        jLabel5.setText("Qte vendue : ");

        jLabel7.setText("(HT)");

        txtVendu.setMinimumSize(new java.awt.Dimension(60, 20));
        txtVendu.setPreferredSize(new java.awt.Dimension(60, 20));

        jLabel8.setText("(TTC)");

        cbCategories.setEditable(true);

        jLabel6.setText("Catégorie :");

        jLabel9.setText("Photo :");

        txtFileName.setEditable(false);
        txtFileName.setText("Aucune");

        btPix.setText("Choisir...");
        btPix.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPixActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addComponent(txtFileName)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btPix))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtStock, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(txtPxAchat, javax.swing.GroupLayout.DEFAULT_SIZE, 63, Short.MAX_VALUE)
                                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel3)
                                            .addComponent(jLabel5))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(txtPxVente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(txtVendu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addComponent(jLabel8)))
                            .addComponent(txtDesignation, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(cbCategories, 0, 211, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtDesignation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtPxAchat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtPxVente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtVendu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(cbCategories, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(btPix))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(imagePan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btOk))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(imagePan, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btOk)
                            .addComponent(btCancel))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelActionPerformed
        doCancel();
    }//GEN-LAST:event_btCancelActionPerformed

    private void btOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btOkActionPerformed
        doAccept();
    }//GEN-LAST:event_btOkActionPerformed

    private void btPixActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPixActionPerformed
        fileChooser.setFileFilter(new ImageFileFilter());
        if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(this)) {
            File f = fileChooser.getSelectedFile();
            String oldFilename = txtFileName.getText();
            txtFileName.setText("Chargement...");
            String fileName = App.saveFile(f);
            if(!"".equals(fileName)){
                Image img = App.createPhoto(fileName);//.getScaledInstance(imagePan.getWidth(), imagePan.getHeight(), Image.SCALE_REPLICATE);
                imagePan.setStyle(Style.SCALED_KEEP_ASPECT_RATIO);
                imagePan.setImage(img);
                txtFileName.setText(fileName);
            } else {
                App.displayMessage("Impossible de charger la photo", 
                        App.MESSAGE_TYPE.ERROR);
                txtFileName.setText(oldFilename);
            }
            
        }
    }//GEN-LAST:event_btPixActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btOk;
    private javax.swing.JButton btPix;
    private javax.swing.JComboBox cbCategories;
    private javax.swing.JFileChooser fileChooser;
    private org.jdesktop.swingx.JXImagePanel imagePan;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtDesignation;
    private javax.swing.JTextField txtFileName;
    private javax.swing.JTextField txtPxAchat;
    private javax.swing.JTextField txtPxVente;
    private javax.swing.JTextField txtStock;
    private javax.swing.JTextField txtVendu;
    // End of variables declaration//GEN-END:variables
}
